package com.lxq.live.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Objects;

@Service
public class AudienceService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    private AudienceService() {
    }

    public synchronized void operation(String videoUuid, boolean flag) {
        ValueOperations<String, String> audiencesKV = stringRedisTemplate.opsForValue();
        String audiences = audiencesKV.get("audiences_" + videoUuid);
        if (audiences == null) {
            audiencesKV.set("audiences_" + videoUuid, "1", Duration.ofSeconds(10));
        } else {
            var currentAudiences = Integer.parseInt(Objects.requireNonNull(audiencesKV.get("audiences_" + videoUuid)));
            if (flag) {
                currentAudiences++;
            } else {
                if (currentAudiences <= 0) {
                    currentAudiences = 0;
                } else {
                    currentAudiences--;
                }
            }
            audiencesKV.set("audiences_" + videoUuid, currentAudiences + "", Duration.ofSeconds(10));
        }
    }

    public int getAudiences(String videoUuid) {
        ValueOperations<String, String> audiencesKV = stringRedisTemplate.opsForValue();
        audiencesKV.set("audiences_" + videoUuid, Objects.requireNonNull(audiencesKV.get("audiences_" + videoUuid)), Duration.ofSeconds(10));
        return Integer.parseInt(Objects.requireNonNull(audiencesKV.get("audiences_" + videoUuid)));
    }
}
